package com.aruba.drawerapplication;

import android.content.Context;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * 侧滑菜单背景view
 */
public class SlideBackgroundView extends View {
    private Paint paint;
    private Path path;
    private int height, width;
    //贝塞尔曲线初始坐标和结束坐标的Y轴偏移
    private float offsetY;
    private float offsetX;

    public SlideBackgroundView(Context context) {
        this(context, null);
    }

    public SlideBackgroundView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        path = new Path();
    }

    /**
     * 处理path，贝塞尔曲线
     *
     * @param y        触摸的y坐标
     * @param fraction 侧滑打开的比例0-1
     */
    public void calcBezier(float y, float fraction) {
        path.reset();

        height = getHeight();
        width = getWidth();
        offsetY = height / 8f;
        offsetX = width / 2f;
        path.moveTo(0, -offsetY);
        path.lineTo(offsetX, -offsetY);
        path.quadTo(width * 3 / 2f * fraction, y, offsetX, height + offsetY);
        path.lineTo(0, height + offsetY);
        path.close();

        invalidate();
    }


    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawPath(path, paint);
    }

    @Override
    public void setBackground(Drawable background) {
        if (background instanceof ColorDrawable) {
            paint.setColor(((ColorDrawable) background).getColor());
        } else if (background instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) background;
            BitmapShader bitmapShader = new BitmapShader(bitmapDrawable.getBitmap(), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            paint.setShader(bitmapShader);
        }
    }
}
